/**
 * @description: 这是Eirudy创建的类~
 * @author: Eirudy
 * @hope: 憧憬成为java大师
 **/

package org.eirudy.shareimage.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.eirudy.shareimage.annotation.AuthCheck;
import org.eirudy.shareimage.common.BaseResponse;
import org.eirudy.shareimage.common.DeleteRequest;
import org.eirudy.shareimage.common.ResultUtils;
import org.eirudy.shareimage.constant.UserConstant;
import org.eirudy.shareimage.exception.BusinessException;
import org.eirudy.shareimage.exception.ErrorCode;
import org.eirudy.shareimage.exception.ThrowUtils;
import org.eirudy.shareimage.manager.CosManager;
import org.eirudy.shareimage.mapper.SpaceMapper;
import org.eirudy.shareimage.model.dto.space.*;
import org.eirudy.shareimage.model.entity.Space;
import org.eirudy.shareimage.model.entity.User;
import org.eirudy.shareimage.model.enums.SpaceLevelEnum;
import org.eirudy.shareimage.model.enums.UserRoleEnum;
import org.eirudy.shareimage.model.vo.SpaceVO;
import org.eirudy.shareimage.service.impl.SpaceServiceImpl;
import org.eirudy.shareimage.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private CosManager cosManager;

    @Resource
    private SpaceServiceImpl spaceService;

    @Resource
    private UserServiceImpl userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();
    @Autowired
    private SpaceMapper spaceMapper;


    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null,ErrorCode.PARAMS_ERROR,"参数为空");
        User loginUser = userService.getLoginUser(request);
        long result = spaceService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 空间删除
     * @param deleteRequest
     * @param request
     * @return
     */
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request){
        if(deleteRequest == null || deleteRequest.getId() == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //接下来校验删除者的身份，如果是管理员或者空间的创建者，就可以删除空间了
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        Space oldSpace = spaceService.getById(id);

        if(oldSpace == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        if(!user.getUserRole().equals(UserConstant.ADMIN_ROLE) && !user.getId().equals(oldSpace.getUserId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        boolean result = spaceService.removeById(id);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"删除失败");

 
        return ResultUtils.success(true);
    }

    /**
     * 更新空间
     * @param spaceUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest,HttpServletRequest request) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }


        Space oldSpace = spaceService.getById(spaceUpdateRequest.getId());
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);

        //实体和dto转换
        Space space = new Space();
        BeanUtil.copyProperties(spaceUpdateRequest, space);

        //校验一下space
        spaceService.validSpace(space,false);

        //补充参数
        User loginuser = userService.getLoginUser(request);
        spaceService.fillSpaceBySpaceLevel(space);

        boolean result = spaceService.updateById(space);

        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        return ResultUtils.success(true);

    }


    /**
     * 管理员特供，根据id获取空间
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);

        if (space == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        return ResultUtils.success(space);
    }

    /**
     *  根据id 获得空间，所有人可用
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVoById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);

        if (space == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        return ResultUtils.success(spaceService.getSpaceVO(space,request));
    }

    /**
     *  获得空间信息分页列表，管理员使用的
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();

        Page<Space> spacePage = spaceService.page(new Page<>(current,size),
                spaceService.getQueryWrapper(spaceQueryRequest));

        return ResultUtils.success(spacePage);
    }

    /**
     * 获得空间信息vo 所有人可用
     * @param spaceQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVoByPage(@RequestBody SpaceQueryRequest spaceQueryRequest, HttpServletRequest request) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();


        Page<Space> spacePage = spaceService.page(new Page<>(current,size),
                spaceService.getQueryWrapper(spaceQueryRequest));

        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage,request));
    }


    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        if(spaceEditRequest == null || spaceEditRequest.getId() == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //仅管理员或者本人可以修改
        User user = userService.getLoginUser(request);
        Space oldSpace = spaceService.getById(spaceEditRequest.getId());

        if(oldSpace == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if(!user.getUserRole().equals(UserConstant.ADMIN_ROLE) && !user.getId().equals(oldSpace.getUserId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }


        //此处进行dto和实体类的转换
        Space space = new Space();
        BeanUtil.copyProperties(spaceEditRequest, space);

        //补充参数
        space.setEditTime(new Date());
        spaceService.fillSpaceBySpaceLevel(space);
        //空间校验
        spaceService.validSpace(space,false);


        //操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);

    }

    @GetMapping("/list/space/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

    @Deprecated
    @GetMapping("/get/vo/userId")
    public BaseResponse<SpaceVO> getSpaceVoByUserId(long id, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        Long userId = user.getId();

        Space space =  spaceMapper.selectSpaceByUserId(userId);

        return ResultUtils.success(spaceService.getSpaceVO(space,request));
    }


}
